<!DOCTYPE html>
<html lang="en">
	<head>
		<title>Uppy</title>
		<meta charset="utf-8">
		<meta name="title" content="Uppy">
		<meta name="description" content="Uppy fetches files locally and from remote places like Dropbox or Instagram. With its seamless integration, reliability and ease of use, Uppy is truly your best friend in file uploading.
">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="twitter:card" content="summary_large_image">
		<meta name="twitter:site" content="@uppy_io">
		<meta name="twitter:creator" content="@uppy_io">
		<meta property="og:url" content="https://uppy.io/index.html">
		<meta property="og:title" content="Uppy">
		<meta name="twitter:title" content="Uppy">
		<meta name="twitter:description" content="Uppy fetches files locally and from remote places like Dropbox or Instagram. With its seamless integration, reliability and ease of use, Uppy is truly your best friend in file uploading.
">
		<meta property="og:image" content="http://uppy.io/images/uppy-social-pink.png">
		<meta name="twitter:image" content="http://uppy.io/images/uppy-social-pink.png">

		<meta name="google-site-verification" content="JxARoHXoCI8bD07pLV_u3z6xpuWNcSIZIcHEytyCkUc" />

		<link rel="icon" href="/images/logos/uppy-dog-head-arrow.png" type="image/x-icon">
		<link rel="alternate" type="application/rss+xml" title="Uppy" href="/atom.xml">

		<script>
			window.PAGE_TYPE = ""
		</script>

		<!-- ^ poor man's solution to css cache busting. bump the version when there's something new we really want users to see -->
		<meta name="generator" content="Hexo 4.2.1">
	</head>
	<body class="page-index ">
		<div class="page">
			<div id="app">
				<el-card class="box-card">
					<template #header>
						<div class="card-header">
							<span>上传说明(选填)</span>
						</div>
					</template>
					<el-input id="fileDescription" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"
						v-model="message" placeholder="详细的文件说明可以更好的找到文件哦(͏ ˉ ꈊ ˉ)✧˖°">
					</el-input>
				</el-card>

				<el-card class="box-card">
					<template #header>
						<div class="card-header">
							<span>文件上传</span>
						</div>
					</template>

					<main class="MainContent js-MainContent" id="main">
						<section class="IndexDemo" style="margin-left: 10%;">
							<div class="IndexDemo-tabContent">
								<div class="TabPane TabPane--active" id="live-demo">
									<div class="IndexDemo-uppyWrapper">
										<div class="IndexDemo-uppy" id="demo"></div>
									</div>
								</div> <!-- /live-demo -->
							</div>
						</section>
					</main>

					<div id="" style="display: flex;align-items: center; width: 80%;
						margin-top: 100px;position: relative; bottom: 50px;left: 10%;
						border-radius: 20px;
						height: 40px;line-height: 40px;" onclick="upload()">
						<input type="button" style=" background-color: #00aaff;
						outline: 0;
						border-radius: 50px;
						width: 100%; height: 100%; font-size: 20px;" id="upload-btn" value="一键上传" />
					</div>
				</el-card>

				<!-- <button type="primary" id="updataBtn"><span class="iconfont iconloading" id="loading" ></span>文件上传</button> -->
			</div>



			<script>
				(function(i, s, o, g, r, a, m) {
					i['GoogleAnalyticsObject'] = r;
					i[r] = i[r] || function() {
						(i[r].q = i[r].q || []).push(arguments)
					}, i[r].l = 1 * new Date();
					a = s.createElement(o),
						m = s.getElementsByTagName(o)[0];
					a.async = 1;
					a.src = g;
					m.parentNode.insertBefore(a, m)
				})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');

				ga('create', 'UA-63083-12', 'uppy.io');
				ga('set', 'anonymizeIp', true);
				ga('send', 'pageview');
			</script>
			
			<link href="https://releases.transloadit.com/uppy/v1.31.0/uppy.min.css" rel="stylesheet">
			<script src="https://releases.transloadit.com/uppy/v1.31.0/uppy.min.js"></script>
			<!-- 引入axios -->
			<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
			<link rel="stylesheet" type="text/css" href="//at.alicdn.com/t/font_1938586_06k5hu69c21f.css">
			<script src="js/spark-md5.min.js"></script>
			<script src="https://unpkg.com/vue@next"></script>
			<!-- import CSS -->
			<link rel="stylesheet" href="https://unpkg.com/element-plus/lib/theme-chalk/index.css">
			<!-- import JavaScript -->
			<script src="https://unpkg.com/element-plus/lib/index.full.js"></script>
			<script>
				var axios = axios
				axios.defaults.baseURL = "http://127.0.0.1:9001"
				// axios.defaults.baseURL = "https://gateway.xiaohong.work/api"
			
				// Vue部分
				const App = {
					data() {
						return {
							message: "",
						};
					},
					created() {
			
					}
				};
				const app = Vue.createApp(App);
				app.use(ElementPlus);
				app.mount("#app");
			
				var FileList = []
			
			
				function sleep(numberMillis) {
					var now = new Date();
					var exitTime = now.getTime() + numberMillis;
					while (true) {
						now = new Date();
						if (now.getTime() > exitTime)
							return;
					}
				}
				var TUS_ENDPOINT = 'http://119.29.67.157:8080/xiaohong/big/upload/'
				var COMPANION_ENDPOINT = 'http://localhost:3020'
				// Uppy初始化
				var uppy = Uppy.Core({
						// 上传文件前钩子
						onBeforeUpload: (files) => {
							const updatedFiles = {}
							Object.keys(files).forEach(async fileID => {
								updatedFiles[fileID] = {
									...files[fileID]
								}
								var md5
								var fileInfo
								console.log("FileList", FileList)
								console.log("fileID", fileID)
								for (var i = 0; i < FileList.length; i++) {
									if (FileList[i].id == fileID) {
										md5 = FileList[i].md5
										fileInfo = FileList[i].fileInfo
										console.log("找到了", FileList[i].fileInfo)
									}
								}
			
								if (fileInfo == "null") {
									console.log(fileID + "之前不存在")
									uppy.use(Uppy.Tus, {
										id: "bigUpload",
										endpoint: TUS_ENDPOINT
									})
								} else if (fileInfo == null) {
									// 数据还没到
									console.log("文件未加载完成")
								} else {
									console.log(fileID + "已经存在")
									// uppy.use(Uppy.XHRUpload, {
									// 	id: "againUpload",
									// 	// endpoint: 'http://127.0.0.1:9001/file/again?md5=' + md5
									// 	endpoint: 'http://127.0.0.1:80'
									// })
									updatedFiles[fileID].progress.bytesUploaded = updatedFiles[fileID]
										.progress
										.bytesTotal
									updatedFiles[fileID].progress.percentage == 100
									updatedFiles[fileID].progress.uploadComplete = true
									updatedFiles[fileID].progress.uploadStarted = new Date().getTime()
			
									//秒传文件直接添加
									var fl = {}
									fl.md5 = md5
									fl.fileDescription = document.getElementById("fileDescription").value
									fl.fileName = updatedFiles[fileID].name
									// var ax = axios
									// ax.defaults.baseURL = "http://127.0.0.1:9001"
									// ax.defaults.baseURL = "https://gateway.xiaohong.work/api"
									// 更新数据
									for (var i = 0; i < FileList.length; i++) {
										if (FileList[i].id == fileID) {
											var newInfo = FileList[i]
											newInfo.fileInfo.fileDescription = fl.fileDescription
											newInfo.fileInfo.fileName = fl.fileName
											FileList.splice(i, 1, newInfo)
											console.log("更新后的数据", FileList)
										}
									}
									// 提交数据
									axios.post("/file/add/quick", {
										...fl,
									}).then(function(res) {
										console.log(JSON.stringify(res))
										// alert(res.data.message);
									}).catch(function(error) {
										console.log(error)
									})
			
									// uppy.use(Uppy.Tus, {
									//   endpoint: 'http://119.29.67.157:8080/xiaohong/upload?md5='+md5+"&output=json"
									// })
								}
							})
							console.log("上传前", updatedFiles)
			
							return updatedFiles
						}
					})
					.use(Uppy.Dashboard, {
						inline: true,
						target: '#demo',
						note: '支持所有文件类型的断点上传',
						// width: 900,
						hideUploadButton: true,
						// height: 750,
						theme: 'bark',
						metaFields: [{
								id: 'name',
								name: 'Name',
								placeholder: 'file name'
							},
							{
								id: 'license',
								name: 'License',
								placeholder: 'specify license'
							},
							{
								id: 'caption',
								name: 'Caption',
								placeholder: 'describe what the image is about'
							},
							{
								id: 'public',
								name: 'Public',
								render: function({
									value,
									onChange
								}, h) {
									return h('input', {
										type: 'checkbox',
										onChange: (ev) => onChange(ev.target.checked ? 'on' : 'off'),
										defaultChecked: value === 'on'
									})
								}
							}
						],
						locale: {
							strings: {
								// When `inline: false`, used as the screen reader label for the button that closes the modal.
								closeModal: '关闭面板',
								// Used as the screen reader label for the plus (+) button that shows the “Add more files” screen
								addMoreFiles: '添加更多文件',
								// TODO
								addingMoreFiles: '添加更多文件',
								// Used as the header for import panels, e.g., “Import from Google Drive”.
								importFrom: 'Import from %{name}',
								// When `inline: false`, used as the screen reader label for the dashboard modal.
								dashboardWindowTitle: 'Uppy Dashboard Window (Press escape to close)',
								// When `inline: true`, used as the screen reader label for the dashboard area.
								dashboardTitle: 'Uppy Dashboard',
								// Shown in the Informer when a link to a file was copied to the clipboard.
								copyLinkToClipboardSuccess: 'Link copied to clipboard.',
								// Used when a link cannot be copied automatically — the user has to select the text from the
								// input element below this string.
								copyLinkToClipboardFallback: 'Copy the URL below',
								// Used as the hover title and screen reader label for buttons that copy a file link.
								copyLink: 'Copy link',
								// Used as the hover title and screen reader label for file source icons, e.g., “File source: Dropbox”.
								fileSource: '完成进度: %{name}',
								// Used as the label for buttons that accept and close panels (remote providers or metadata editor)
								done: '完成',
								// TODO
								back: '返回',
								// Used as the screen reader label for buttons that remove a file.
								removeFile: 'Remove file',
								// Used as the screen reader label for buttons that open the metadata editor panel for a file.
								editFile: 'Edit file',
								// Shown in the panel header for the metadata editor. Rendered as “Editing image.png”.
								editing: 'Editing %{file}',
								// Text for a button shown on the file preview, used to edit file metadata
								edit: '编辑',
								// Used as the screen reader label for the button that saves metadata edits and returns to the
								// file list view.
								finishEditingFile: 'Finish editing file',
								// TODO
								saveChanges: 'Save changes',
								// Used as the label for the tab button that opens the system file selection dialog.
								myDevice: '本地文件',
								// Shown in the main dashboard area when no files have been selected, and one or more
								// remote provider plugins are in use. %{browse} is replaced with a link that opens the system
								// file selection dialog.
								dropPasteImport: '将文件复制粘贴到这,或者 %{browse} 又或者导入文件从',
								// Shown in the main dashboard area when no files have been selected, and no provider
								// plugins are in use. %{browse} is replaced with a link that opens the system
								// file selection dialog.
								dropPaste: '拖拽或复制你的文件到这，又或者浏览本地文件',
								// TODO
								dropHint: '将你的文件拖拽到这',
								// This string is clickable and opens the system file selection dialog.
								browse: '浏览本地文件',
								// Used as the hover text and screen reader label for file progress indicators when
								// they have been fully uploaded.
								uploadComplete: '上传完成',
								// TODO
								uploadPaused: 'Upload paused',
								// Used as the hover text and screen reader label for the buttons to resume paused uploads.
								resumeUpload: 'Resume upload',
								// Used as the hover text and screen reader label for the buttons to pause uploads.
								pauseUpload: '暂停',
								// Used as the hover text and screen reader label for the buttons to retry failed uploads.
								retryUpload: '重试',
								// Used as the hover text and screen reader label for the buttons to cancel uploads.
								cancelUpload: '取消',
			
								// Used in a title, how many files are currently selected
								xFilesSelected: {
									0: '%{smart_count} file selected',
									1: '%{smart_count} files selected'
								},
								// TODO
								uploadingXFiles: {
									0: 'Uploading %{smart_count} file',
									1: 'Uploading %{smart_count} files'
								},
								// TODO
								processingXFiles: {
									0: 'Processing %{smart_count} file',
									1: 'Processing %{smart_count} files'
								},
			
								// The "powered by Uppy" link at the bottom of the Dashboard.
								// **NOTE**: This string is called `poweredBy2` for backwards compatibility reasons.
								// See https://github.com/transloadit/uppy/pull/2077
								poweredBy2: '本服务由小鸿同学提供',
			
								// @uppy/status-bar strings:
								uploading: '上传中',
								complete: '上传完成'
							}
						}
					})
					.use(Uppy.Webcam, {
						inline: true,
						target: Uppy.Dashboard
					})
					// .use(Uppy.ScreenCapture, {
					// 	target: Uppy.Dashboard
					// })
					.use(Uppy.ImageEditor, {
						target: Uppy.Dashboard
					})
					.use(Uppy.GoogleDrive, {
						target: Uppy.Dashboard,
						companionUrl: COMPANION_ENDPOINT
					})
					.use(Uppy.Instagram, {
						target: Uppy.Dashboard,
						companionUrl: COMPANION_ENDPOINT
					})
					.use(Uppy.Dropbox, {
						target: Uppy.Dashboard,
						companionUrl: COMPANION_ENDPOINT
					})
					.use(Uppy.Box, {
						target: Uppy.Dashboard,
						companionUrl: COMPANION_ENDPOINT
					})
					.use(Uppy.Facebook, {
						target: Uppy.Dashboard,
						companionUrl: COMPANION_ENDPOINT
					})
					.use(Uppy.OneDrive, {
						target: Uppy.Dashboard,
						companionUrl: COMPANION_ENDPOINT
					})
					.use(Uppy.Url, {
						target: Uppy.Dashboard,
						companionUrl: COMPANION_ENDPOINT
					})
			
			
				// uppy.setMeta({ callback_url:'https://gateway.xiaohong.work/api/file/callback'})//自定义参数与普通上传类似（虽然支持自定义，建议不要自定义，海量文件情况下，自定义很可能给自已给埋坑）
			
			
				uppy.on('file-added', (file) => {
					// document.getElementById("updataBtn").removeAttribute()("disabled");
					document.getElementById("upload-btn").setAttribute("disabled", "disabled");
					document.getElementById("upload-btn").setAttribute("value", "文件加载中....");
					var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
						fileInfo = file.data
					chunkSize = 2097152, // Read in chunks of 2MB
						chunks = Math.ceil(fileInfo.size / chunkSize),
						currentChunk = 0,
						spark = new SparkMD5.ArrayBuffer(),
						fileReader = new FileReader();
			
					fileReader.onload = async function(e) {
						// console.log('read chunk nr', currentChunk + 1, 'of', chunks);
						spark.append(e.target.result); // Append array buffer
						currentChunk++;
			
						if (currentChunk < chunks) {
							loadNext();
						} else {
							// 这里注意 多次获取的值不一样
							// console.info('computed hash', spark.end()); // Compute hash
							var md5 = spark.end()
							console.info('computed hash', md5); // Compute hash
							var fileInfo
							// var axo = axios
							// axios.defaults.baseURL ="https://gateway.xiaohong.work/api"
							// axo.defaults.baseURL ="http://127.0.0.1:9001"
							await axios.get("/file/searchByMD5?md5=" + md5)
								.then(function(res) {
									console.log(JSON.stringify(res))
									// console.log(res.data.message);
									console.log(res.data)
									fileInfo = res.data.data
									// 去除loading和打开按钮
									// document.getElementById("upload-btn").innerHTML("<p>等待上传</p>");
									document.getElementById("upload-btn").removeAttribute("disabled");
									document.getElementById("upload-btn").setAttribute("value", "一键上传");
								}).catch(function(error) {
									console.log(error)
								})
			
							// 获取文件信息
							FileList.push({
								id: file.id,
								md5: md5,
								fileInfo: fileInfo
							})
							uppy.getPlugin('Dashboard').setOptions({
								hideUploadButton: false
							})
							console.log("添加后文件集合", FileList)
						}
					};
			
					fileReader.onerror = function() {
						console.warn('oops, something went wrong.');
					};
			
					function loadNext() {
						var start = currentChunk * chunkSize,
							end = ((start + chunkSize) >= fileInfo.size) ? fileInfo.size : start + chunkSize;
			
						fileReader.readAsArrayBuffer(blobSlice.call(fileInfo, start, end));
					}
			
					loadNext();
			
				})
			
			
				function upload() {
					if (FileList.length == 0 || FileList == null) {
						alert("你还没有添加文件哦~")
						return
					}
					var flag = true
					FileList.forEach(file => {
						if (file.fileInfo == null) {
							flag = false
						}
					})
					if (flag) {
						if (document.getElementById("fileDescription").value == '') {
							alert("请先填写文件简介哦~")
						} else {
							uppy.upload()
							// .then((result) => {
							//   console.info('Successful uploads:', result.successful)
			
							//   if (result.failed.length > 0) {
							//     console.error('Errors:')
							//     result.failed.forEach((file) => {
							//       console.error(file.error)
							//     })
							//   }
							// })
						}
					} else {
						alert("文件加载中...")
					}
				}
			
			
				function isUpload() {
					var flag = true
					FileList.forEach(file => {
						if (file.fileInfo == null) {
							flag = false
						}
					})
					if (flag) {
						// return true
						document.getElementById("upload-btn").removeAttribute("disabled");
						document.getElementById("upload-btn").setAttribute("value", "一键上传");
					} else {
						// 不可上传
						document.getElementById("upload-btn").setAttribute("disabled", "disabled");
						document.getElementById("upload-btn").setAttribute("value", "文件加载中....");
						// return false
					}
				}
			
				uppy.on('file-removed', (file, reason) => {
					console.log('Removed file', file)
					for (var i = 0; i < this.FileList.length; i++) {
						if (this.FileList[i].id == file.id) {
							this.FileList.splice(i, 1)
						}
					}
					isUpload()
					console.log("删除文件集合", FileList)
				})
			
				var fileInfo = {
					fileName: '',
					fileSize: '',
					extension: '',
					fileGroup: 'xiaohong',
					fileDescription: '',
					domain: 'https://file.xiaohong.work',
					path: "",
					md5: ''
				}
			
				uppy.on('complete', async result => {
					console.log('successful files:', result.successful)
					console.log('failed files:', result.failed)
					if (result.successful.length > 0) {
						// 代表上传成功 遍历保存数据
						for (var i = 0; i < result.successful.length; i++) {
							console.log(JSON.stringify(result.successful[i]))
							this.fileInfo.fileName = result.successful[i].name
							// this.fileInfo.fileSize = result.successful[i].size
							this.fileInfo.extension = result.successful[i].name.split('.').pop()
							this.fileInfo.fileDescription = document.getElementById("fileDescription").value
							// console.log("value:" + document.getElementById("fileDescription").value)
							// axios.defaults.baseURL = ''
							// axios.defaults.baseURL = 'https://gateway.xiaohong.work/api'
							// axios.defaults.baseURL = 'http://119.29.67.157:9004'
							// axios.defaults.baseURL = 'http://127.0.0.1:9001'
			
			
			
							// 删除元素
							// for (var i = 0; i < this.FileList.length; i++) {
							// 	if(this.FileList[i].id == result.successful[i].id){
							// 		this.FileList[i].splice(i,1)
							// 	}
							// }
							this.fileInfo.path = "/xiaohong" + result.successful[i].uploadURL.split('/xiaohong')
							.pop()
							this.fileInfo.md5 = result.successful[i].uploadURL.split('/').pop()
							axios.post("/file/add", {
								...this.fileInfo,
							}).then(function(res) {
								console.log(JSON.stringify(res))
								console.log(res.data.message);
							}).catch(function(error) {
								console.log(error)
							})
			
			
						}
			
					}
				})
			</script>


			<!-- 			<script src="js/jquery-3.6.0.min.js"></script>
			<script src="//kvz.github.io/on-the-githubs/js/jquery.on-the-githubs.min.js"></script>
			<script type="text/javascript">
				$('.on-the-githubs').onthegithubs();
			</script> -->

			<script src="/js/common.js"></script>

			<!-- Twitter follow button script -->
			<script>
				! function(d, s, id) {
					var js, fjs = d.getElementsByTagName(s)[0],
						p = /^http:/.test(d.location) ? 'http' : 'https';
					if (!d.getElementById(id)) {
						js = d.createElement(s);
						js.id = id;
						js.src = p + '://platform.twitter.com/widgets.js';
						fjs.parentNode.insertBefore(js, fjs);
					}
				}(document, 'script', 'twitter-wjs');
			</script>
		</div>
	</body>
</html>
